﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Explore
{
    public partial class Explorer : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public Explorer()
        {
            InitializeComponent();

            lvwColumnSorter = new ListViewSort();
            listView.ListViewItemSorter = lvwColumnSorter;
            listView.Sorting = SortOrder.Ascending;
        }

        string TempName;                    ////Lưu lại tên trước khi sửa tên 1 đói tượng
        string pathLink;                    //đường dẫn thư mục hiện tại
        TreeNode NodeSelected;              //lưu lại vị trí node đang chọn
        Stack BackStack = new Stack();      //Lưu danh sách các node đã đi qua để bấm nút back
        Stack ForStack = new Stack();       //Lưu danh sách các node đã đi qua để bấm nút forwad
        bool strfile = true;                //true-listview_selected_file; 
                                            //false-listview_selected_folder

        private void Form1_Load(object sender, EventArgs e)
        {
            InitTreeView();
            treeView.SelectedNode = treeView.Nodes[1];
            treeView.HideSelection = false;

            group_file.Enabled = false;
            group_edit.Enabled = false;
            group_label.Enabled = false;


        }

        #region "Setup TreeView"

        private void treeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            Expand(e.Node);
        }

        void Expand(TreeNode node)
        {
            if (node.FullPath == "MyComputer") return;
            node.Nodes.Clear();
            DirectoryInfo dirlistview;
            dirlistview = new DirectoryInfo(Explore.FullPath(node));
            foreach (DirectoryInfo file in dirlistview.GetDirectories())
            {
                if ((file.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden && (file.Attributes & FileAttributes.System) != FileAttributes.System)
                {
                    TreeNode tn = new TreeNode();
                    tn.Name = file.Name;
                    tn.Text = file.Name;
                    tn.Tag = file.Name;
                    node.Nodes.Add(tn);
                    try
                    {
                        string[] dirs = Directory.GetDirectories(Explore.FullPath(tn));
                        if (dirs.Length > 0) tn.Nodes.Add("");
                    }
                    catch
                    { }
                }
            }

        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {

            if (e.Node.FullPath.Contains("MyComputer\\"))   
            {
                cmb_link.Text = e.Node.FullPath.Substring(11);
                pathLink = cmb_link.Text;
            }
            else
            {
                cmb_link.Text = e.Node.FullPath;
                string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                pathLink = path.Substring(0, path.IndexOf("Documents")) + cmb_link.Text;
            }
            if (treeView.SelectedNode == treeView.Nodes[0]) pathLink = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (treeView.SelectedNode == treeView.Nodes[1]) pathLink = System.Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);

            ShowListview(pathLink);

            NodeSelected = treeView.SelectedNode;
            BackStack.Push(NodeSelected);

        }

        void InitTreeView()
        {
            TreeNode MyDocuments = new TreeNode();
            MyDocuments.Name = "Documents";
            MyDocuments.Text = "Documents";
            MyDocuments.Tag = "Documents";
            MyDocuments.ImageKey = "Documents.png";
            MyDocuments.SelectedImageKey = "Documents.png";

            TreeNode Mycomputer = new TreeNode();
            Mycomputer.Name = "MyComputer";
            Mycomputer.Text = "MyComputer";
            Mycomputer.Tag = "MyComputer";
            Mycomputer.ImageKey = "MyComputer.png";
            Mycomputer.SelectedImageKey = "MyComputer.png";

            treeView.Nodes.Add(MyDocuments);
            treeView.Nodes.Add(Mycomputer);

            //Thêm vào các ổ đĩa trong Mycomputer
            DriveInfo[] allDrives = DriveInfo.GetDrives();
            foreach (DriveInfo Driver in allDrives)
            {
                if (Driver.IsReady)
                {
                    TreeNode tn = new TreeNode();
                    tn.Name = Driver.Name;
                    tn.Text = Driver.Name;
                    tn.Tag = Driver.Name;
                    tn.ImageKey = "Driver.png";
                    tn.SelectedImageKey = "Driver.png";
                    Mycomputer.Nodes.Add(tn);
                    if (Explore.ExistsChildNode(tn))
                        tn.Nodes.Add(string.Empty);
                }
            }

            //Thêm vào thư mục con trong MyDucuments
            string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            DirectoryInfo dirlistview = new DirectoryInfo(path);
            foreach (DirectoryInfo file in dirlistview.GetDirectories())
            {
                if ((file.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden && (file.Attributes & FileAttributes.System) != FileAttributes.System)
                {
                    TreeNode tn = new TreeNode();
                    tn.Name = file.Name;
                    tn.Text = file.Name;
                    tn.Tag = file.Name;
                    MyDocuments.Nodes.Add(tn);
                    try
                    {
                        string[] dirs = Directory.GetDirectories(tn.FullPath);
                        if (dirs.Length > 0) tn.Nodes.Add("");
                    }
                    catch
                    { }
                }
            }
        }

        #endregion

        #region "Setup ListView"

        private void listView_DoubleClick(object sender, EventArgs e)
        {
            ListViewItem it = listView.SelectedItems[0];
            try                     //nếu là Folder
            {
                TreeNode node = treeView.SelectedNode;
                node.Expand();
                Expand(node);
                treeView.SelectedNode = node.Nodes[it.Index];
            }
            catch (Exception)      //Nếu là File ảnh
            {
                ShowImage.pathImage = pathLink + "\\" + it.Text;
                ShowImage frm = new ShowImage();
                frm.ShowDialog();

            }
        }

        private void listView_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (pathLink == "") //Thao tác trên ổ đĩa hệ thống
            {
                e.CancelEdit=true;
                return; 
            }
            try     //Thao tác trên folder
            {
                GC.Collect();
                Directory.Move(pathLink + "\\" + TempName, pathLink + "\\" + e.Label);
            }
            catch (Exception)
            {
                try //Thao tác trên file ảnh
                {
                    GC.Collect();
                    System.IO.File.Move(pathLink + "\\" + TempName, pathLink + "\\" + e.Label);
                }
                catch       //Hủy thao tác nếu thao tác trên file hệ thống không cho phép đổi tên
                { 
                    e.CancelEdit=true;
                }
            }
            


        }

        private void listView_BeforeLabelEdit(object sender, LabelEditEventArgs e)
        {
            TempName = listView.SelectedItems[0].Text;  //Lưu lại tên trước khi sửa
        }

        private void listView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            ShowStatus();
            try         
            {
                ListViewItem it = listView.SelectedItems[0];
                TreeNode node = treeView.SelectedNode;

                treeView.BeginUpdate();
                node.Expand();
                Expand(node);
                treeView.EndUpdate();
                NodeSelected = node.Nodes[it.Index];
            }
            catch (Exception)
            {

            }
        }

        private void listView_Click(object sender, EventArgs e)
        {
            if (!(listView.SelectedItems[0].Text.ToLower().Contains(".png") || listView.SelectedItems[0].Text.ToLower().Contains(".jpg")))
            {
                strfile = false;
            }
            else strfile = true;

            group_file.Enabled = true;
            group_edit.Enabled = true;
            group_label.Enabled = true;
        }

        private void listView_Leave(object sender, EventArgs e)
        {
            group_file.Enabled = false;
            group_edit.Enabled = false;
            group_label.Enabled = false;
        }

        void ShowListview(string path)
        {
            this.Cursor = Cursors.WaitCursor;
            LargeimageList.Images.Clear();
            LargeimageList.Images.Add(Resource.Folder);
            LargeimageList.Images.Add(Resource.Driver);
            listView.Items.Clear();
            int i = 0;
            try
            {
                DirectoryInfo dirlistview = new DirectoryInfo(path);

                //Thêm folder
                foreach (DirectoryInfo file in dirlistview.GetDirectories())  
                {
                    if ((file.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden && (file.Attributes & FileAttributes.System) != FileAttributes.System)
                    {
                        listView.Items.Add(file.Name, 0);
                    }
                }

                //Thêm Ảnh
                foreach (FileInfo file in dirlistview.GetFiles())
                {
                    if (file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".png")
                    {
                        string dateCreate = file.CreationTime.ToString();
                        string type = file.Extension.Substring(1);
                        string size = file.Length / 1024 + " KB";

                        LargeimageList.Images.Add(new Bitmap(Image.FromFile(file.FullName), 100, 100));

                        ListViewItem it = new ListViewItem(file.FullName.Substring(path.Length));
                        it.ImageIndex = i + 2;
                        ListViewItem.ListViewSubItem column_dateCreate = new ListViewItem.ListViewSubItem(it, dateCreate);
                        ListViewItem.ListViewSubItem column_type = new ListViewItem.ListViewSubItem(it, type);
                        ListViewItem.ListViewSubItem column_size = new ListViewItem.ListViewSubItem(it, size);

                        it.SubItems.Add(column_dateCreate);
                        it.SubItems.Add(column_type);
                        it.SubItems.Add(column_size);

                        #region "add rate"
                        if (file.LastWriteTime.ToString() == "12/12/1999 12:00:01 AM")
                        {
                            ListViewItem.ListViewSubItem column_rate = new ListViewItem.ListViewSubItem(it, "*");
                            it.SubItems.Add(column_rate);
                        }
                        if (file.LastWriteTime.ToString() == "12/12/1999 12:00:02 AM")
                        {
                            ListViewItem.ListViewSubItem column_rate = new ListViewItem.ListViewSubItem(it, "**");
                            it.SubItems.Add(column_rate);
                        }
                        if (file.LastWriteTime.ToString() == "12/12/1999 12:00:03 AM")
                        {
                            ListViewItem.ListViewSubItem column_rate = new ListViewItem.ListViewSubItem(it, "***");
                            it.SubItems.Add(column_rate);
                        }
                        if (file.LastWriteTime.ToString() == "12/12/1999 12:00:04 AM")
                        {
                            ListViewItem.ListViewSubItem column_rate = new ListViewItem.ListViewSubItem(it, "****");
                            it.SubItems.Add(column_rate);
                        }
                        if (file.LastWriteTime.ToString() == "12/12/1999 12:00:05 AM")
                        {
                            ListViewItem.ListViewSubItem column_rate = new ListViewItem.ListViewSubItem(it, "*****");
                            it.SubItems.Add(column_rate);
                        }
                        #endregion

                        listView.Items.Add(it);

                        i++;
                        GC.Collect();
                    }
                }
            }
            //Thêm Driver
            catch (Exception)
            {
                DriveInfo[] allDrives = DriveInfo.GetDrives();
                foreach (DriveInfo Driver in allDrives)
                {
                    if (Driver.IsReady)
                    {
                        ListViewItem it = new ListViewItem();
                        listView.Items.Add(Driver.Name, 1);
                        i++;
                        GC.Collect();
                    }
                }
            }
            this.Cursor = Cursors.Default;
        }

        #endregion

        #region "Driver_Info- File_Info"

        private void btn_info_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Info();
        }

        private void infoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Info();
        }

        void Info()
        {
            try
            {
                if (treeView.SelectedNode.Text == "MyComputer") driverInfo(listView.SelectedItems[0].Text);
                else if (treeView.SelectedNode.Text == "Documents") fileInfo(pathLink.Substring(0, pathLink.IndexOf("Documents")) + listView.SelectedItems[0].Text);
                else fileInfo(pathLink + "\\" + listView.SelectedItems[0].Text);
            }
            catch (Exception) { }
        }
        
        void fileInfo(string path)
        {

            DoAn1.fileInfo.path = path;
            DoAn1.fileInfo frm = new DoAn1.fileInfo();
            frm.ShowDialog();
        }
        
        void driverInfo(string path)
        {
            DoAn1.DriverInfo.path = path;
            DoAn1.DriverInfo frm = new DoAn1.DriverInfo();
            frm.ShowDialog();
        }

        #endregion

        #region "NewFolder"

        private void btn_newfolder_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            NewFolder();
        }

        private void newFolderToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NewFolder();
        }

        void NewFolder()
        {
            string newPath = NewFolder(pathLink);
            if (newPath == null)
            {
                MessageBox.Show("Không thể tạo thư mục ở đây", "Lỗi");
                return;
            }
            treeView.SelectedNode.Nodes.Add(newPath.Substring(1));
            ShowListview(pathLink);
        }

        string NewFolder(string path)
        {
            int i = 0;
            DirectoryInfo di;
            string NammeNewFile = "\\New Folder";
            try
            {
                do
                {
                    if (i == 0)
                    {
                        di = new DirectoryInfo(path + "\\" + NammeNewFile);
                        i++;
                    }
                    else
                    {
                        NammeNewFile = "\\New Folder" + " (" + i.ToString() + ")";
                        di = new DirectoryInfo(path + NammeNewFile);
                        i++;
                    }
                } while (di.Exists);
                di.Create();
            }
            catch (Exception)
            {
                return null;
            }
            return NammeNewFile;
        }

        #endregion

        #region "Delete"

        private void btn_delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Delete();
        }

        private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Delete();
        }

        void Delete()
        {
            //Kiểm tra nếu chưa chọn item để xóa
            try
            {
                string strtest = listView.SelectedItems[0].Text;
            }
            catch { return; }
            GC.Collect();
            //Thao tác xóa folder
            if (!strfile)
            {
                if (MessageBox.Show("Có muốn xóa Thư mục " + listView.SelectedItems[0].Text, "Hỏi", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
                int i = listView.SelectedItems[0].Index;
                if (Delete(pathLink + "\\" + listView.SelectedItems[0].Text) == false)
                {
                    MessageBox.Show("Không thể xóa Thư mục hệ thống","Lỗi"); 
                    return; 
                }
                treeView.SelectedNode.Nodes.RemoveAt(i);
            }
            //Thao tác Xóa file
            else
            {
                if (MessageBox.Show("Có muốn xóa Ảnh " + listView.SelectedItems[0].Text, "Hỏi", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
                GC.Collect();
                System.IO.File.Delete(pathLink + "\\" + listView.SelectedItems[0].Text);
            }
            ShowListview(pathLink);
        }

        //Xóa toàn bộ folder và file trong folder có link "path"
        bool Delete(string path)
        {
            try
            {
                DirectoryInfo dirs = new DirectoryInfo(path);
                foreach (FileInfo file in dirs.GetFiles())
                {
                    GC.Collect();
                    file.Delete();
                }
                foreach (DirectoryInfo dir in dirs.GetDirectories())
                {
                    GC.Collect();
                    dir.Delete(true);
                }
                GC.Collect();
                dirs.Delete();
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        #endregion

        #region "Button Back-Forwad-Up"
        private void btn_back_Click(object sender, EventArgs e)
        {
            if (BackStack.Count > 0)
            {
                treeView.SelectedNode = (TreeNode)BackStack.Pop();
                ForStack.Push(treeView.SelectedNode);
            }
        }

        private void bnt_up_Click(object sender, EventArgs e)
        {
            try
            {
                treeView.SelectedNode.Collapse();
                treeView.SelectedNode = treeView.SelectedNode.Parent;
            }
            catch (Exception) { }
        }

        private void btn_forward_Click(object sender, EventArgs e)
        {
            if (ForStack.Count > 0)
                treeView.SelectedNode = (TreeNode)ForStack.Pop();
        }
        #endregion

        void ShowStatus()
        {
            //Hiển thị số Items có trong thư mục
            lbl_tatolItem.Text = listView.Items.Count.ToString() + " Items";

            //Hiển thị số Items dduwwocj chọn
            ListView.SelectedListViewItemCollection breakfast = listView.SelectedItems;
            lbl_selectedItem.Text = breakfast.Count.ToString() + " Selected";

            //Hiển thị dung lượng của các bức ảnh được chọn
            string[] strs = new string[breakfast.Count];
            int i = 0;
            foreach (ListViewItem it in breakfast)
            {
                strs[i] = pathLink + "\\" + it.Text; ;
                i++;
            }
            long totalSize = 0;
            try
            {
                foreach (string str in strs)
                {
                    FileInfo fileInfo = new FileInfo(str);
                    totalSize += fileInfo.Length / 1024;
                }
                lbl_mb.Text = "- " + totalSize.ToString() + " KB";
            }
            catch (Exception)
            {
                lbl_mb.Text = "";
            }
        }

        #region "SelectAllItems"

        private void btn_selectall_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            foreach (ListViewItem it in listView.Items)
            {
                listView.Items[it.Index].Selected = true;
            }
        }

        private void btn_deselectall_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            foreach (ListViewItem it in listView.Items)
            {
                listView.Items[it.Index].Selected = false;
            }
        }


        private void btn_inverselection_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            foreach (ListViewItem it in listView.Items)
            {
                if (listView.Items[it.Index].Selected == true) listView.Items[it.Index].Selected = false;
                else listView.Items[it.Index].Selected = true;
            }
        }

        #endregion

        #region "Search"
        private void txt_search_Click(object sender, EventArgs e)
        {
            txt_search.Text = "";
        }

        private void txt_search_Leave(object sender, EventArgs e)
        {
            txt_search.Text = "Search";
        }

        private void txt_search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                foreach (ListViewItem it in listView.Items)
                {
                    treeView.HideSelection = false;
                    if (!it.Text.Contains(txt_search.Text)) listView.Items.RemoveAt(it.Index);
                }
            }
        }

        #endregion

        #region "ViewListView"

        private void btn_thumnai_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            listView.View = System.Windows.Forms.View.LargeIcon;
        }


        private void btn_list_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            listView.View = System.Windows.Forms.View.List;
        }

        private void btn_details_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            listView.View = System.Windows.Forms.View.Details;
        }

        private void trackBar_MouseMove(object sender, MouseEventArgs e)
        {
            if (trackBar.Value == 0) listView.View = System.Windows.Forms.View.List;
            if (trackBar.Value == 1) listView.View = System.Windows.Forms.View.Details;
            if (trackBar.Value == 2) listView.View = System.Windows.Forms.View.LargeIcon;
        }

        #endregion

        #region "Set Rate"

        private void btn_1start_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                FileInfo file = new FileInfo(pathLink + "\\" + listView.SelectedItems[0].Text);
                file.LastWriteTime = new DateTime(1999, 12, 12, 0, 0, 1);
            }
            catch (Exception)
            {
                MessageBox.Show("Phải chọn một ảnh để thiết lập", "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ShowListview(pathLink);
        }

        private void btn_2star_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                FileInfo file = new FileInfo(pathLink + "\\" + listView.SelectedItems[0].Text);
                file.LastWriteTime = new DateTime(1999, 12, 12, 0, 0, 2);
            }
            catch (Exception)
            {
                MessageBox.Show("Phải chọn một ảnh để thiết lập", "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ShowListview(pathLink);
        }

        private void btn_3star_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                FileInfo file = new FileInfo(pathLink + "\\" + listView.SelectedItems[0].Text);
                file.LastWriteTime = new DateTime(1999, 12, 12, 0, 0, 3);
            }
            catch (Exception)
            {
                MessageBox.Show("Phải chọn một ảnh để thiết lập", "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ShowListview(pathLink);
        }

        private void btn_4star_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                FileInfo file = new FileInfo(pathLink + "\\" + listView.SelectedItems[0].Text);
                file.LastWriteTime = new DateTime(1999, 12, 12, 0, 0, 4);
            }
            catch (Exception)
            {
                MessageBox.Show("Phải chọn một ảnh để thiết lập", "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ShowListview(pathLink);
        }

        private void btn_5star_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                FileInfo file = new FileInfo(pathLink + "\\" + listView.SelectedItems[0].Text);
                file.LastWriteTime = new DateTime(1999, 12, 12, 0, 0, 5);
            }
            catch (Exception)
            {
                MessageBox.Show("Phải chọn một ảnh để thiết lập", "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ShowListview(pathLink);
        }
        #endregion

        #region "Sort"
        private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            ListViewSort(e.Column);
        }

        private void btn_byname_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ListViewSort(0);
        }

        private void btn_date_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ListViewSort(1);
        }

        private void btn_type_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ListViewSort(2);
        }

        private void btn_size_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ListViewSort(3);
        }

        private void btn_rating_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ListViewSort(4);
        }

        private ListViewSort lvwColumnSorter = null;

        void ListViewSort(int column)
        {

            ListView myListView = (ListView)listView;
            if (column == lvwColumnSorter.ColumnToSort)
            {
                if (lvwColumnSorter.OrderOfSort == SortOrder.Ascending)
                {
                    lvwColumnSorter.OrderOfSort = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.OrderOfSort = SortOrder.Ascending;
                }
            }
            else
            {
                lvwColumnSorter.ColumnToSort = column;
                lvwColumnSorter.OrderOfSort = SortOrder.Ascending;
            }

            myListView.Sort();
        }

        #endregion

        #region "Action Copy-Cut"

        string strlistViewSelect;           //Chứa tên file chọn trên listview
        string pathCoppy = null;
        string pathCut = null;

        void Coppy()
        {
           //Kiểm tra nếu chưa chọn item để coppy
            try
            {
                string strtest = listView.SelectedItems[0].Text;
            }
            catch { return; }
            pathCut = null;
            pathCoppy = pathLink + "\\" + listView.SelectedItems[0].Text;
            strlistViewSelect = listView.SelectedItems[0].Text;
        }

        void Cut()
        {
            //Kiểm tra nếu chưa chọn item để Cut
            try
            {
                string strtest = listView.SelectedItems[0].Text;
            }
            catch { return; }
            if (cmb_link.Text.Contains("MyComputer"))
            {
                MessageBox.Show("Không được thao tác trên ổ đĩa hệ thống", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            pathCoppy = null;
            pathCut = pathLink + "\\" + listView.SelectedItems[0].Text;
            strlistViewSelect = listView.SelectedItems[0].Text;
            if (!strfile)//kiem tra xem co phai move folder
            {
                treeView.SelectedNode.Nodes.RemoveByKey(listView.SelectedItems[0].Text);
                strfile = false;
            }
        }

        void Past()
        {
            GC.Collect();
            if (pathCut == null && pathCoppy == null) return;

            //Lấy đường dẫn đích
            string pathTaget;
            try
            {
                pathTaget = pathLink + listView.SelectedItems[0].Text;
            }
            catch (Exception)
            {
                pathTaget = pathLink;
            }
            if (pathCut == pathTaget + "\\" + strlistViewSelect || pathCoppy == pathTaget + "\\" + strlistViewSelect) return;

            //Thực hiện folder
            if (!strfile)
            {
                DirectoryInfo diTarget = new DirectoryInfo(pathTaget + "\\" + strlistViewSelect);
                if (diTarget.Exists == false) diTarget.Create();
                DirectoryInfo diSource;
                try
                {
                    diSource = new DirectoryInfo(pathCoppy);
                }
                catch (Exception)
                {
                    diSource = new DirectoryInfo(pathCut);
                }
                CopyAll(diSource, diTarget);
                if (pathCut != null)
                {
                    Delete(pathCut);
                }
                treeView.BeginUpdate();
                treeView.SelectedNode.Nodes.Add("");
                treeView.SelectedNode.Collapse();
                treeView.SelectedNode.Expand();
                treeView.EndUpdate();
            }

            //Thực hiện file
            else
            {
                if (pathCut != null)
                {
                    System.IO.File.Move(pathCut, pathTaget + "\\" + strlistViewSelect);
                }
                if (pathCoppy != null)
                {
                    System.IO.File.Copy(pathCoppy, pathTaget + "\\" + strlistViewSelect);
                }
            }

            ShowListview(pathLink);
        }

        void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {
            //Kiểm tra xem nơi copy và nơi dán có trùng nhau không
            if (source.FullName.ToLower() == target.FullName.ToLower())
            {
                return;
            }

            //Tạo file nơi đến
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            // Copy từng file 
            foreach (FileInfo fi in source.GetFiles())
            {
                fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }

            // Copy từng folder. 
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetSubDir =
                    target.CreateSubdirectory(diSourceSubDir.Name);
                CopyAll(diSourceSubDir, nextTargetSubDir);
            }
        }

        private void copyToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Coppy();
        }

        private void btn_coppyto_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Coppy();
        }

        private void pastToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Past();
        }

        private void btn_pasthere_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Past();
        }

        private void cutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Cut();
        }

        private void btn_moveto_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Cut();
        }

        #endregion

        private void btn_close_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBox.Show("Có muốn thoát chương trình", "Hỏi", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                Application.Exit();
        }

        private void btn_about_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void listView_KeyUp(object sender, KeyEventArgs e)
        {
            //Nhấn Phím Delete
            if (e.KeyCode == Keys.Delete) Delete();

            //Nhấn phím Ctrl+A 
            //Thực hiện chức năng Select All
            if (e.Control)
            {
                if (e.KeyCode == Keys.A) btn_selectall_ItemClick(null, null);
            }

            //Nhấn Phím Ctrl+C 
            //Thực hiện chức năng coppy
            if (e.Control)
            {
                if (e.KeyCode == Keys.C) copyToolStripMenuItem1_Click(null, null);
            }

            //Nhấn phím Ctrl+V
            //Thực hiện chức năng Past
            if (e.Control)
            {
                if (e.KeyCode == Keys.V) pastToolStripMenuItem1_Click(null, null);
            }
        }



























    }
}
